package com.lj.sys.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.lj.mp.standard.StandardServiceImpl;
import com.lj.sys.entity.SysUserRole;
import com.lj.sys.mapper.SysUserRoleMapper;
import com.lj.sys.service.SysUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户角色关联表 服务实现类
 * </p>
 *
 * @author lj
 * @since 2024-12-10 17:08:40
 */
@Service
public class SysUserRoleServiceImpl extends StandardServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refresh(Long userId, Set<Long> roleIdList) {
        // 用户拥有的角色与主键id的映射
        Map<Long, Long> roleIdOfIdMap = this.getByUserId(userId)
                .stream().collect(Collectors.toMap(SysUserRole::getRoleId, SysUserRole::getId));
        // 需要删除得角色id
        List<Long> deleteRoleIdList = CollUtil.subtractToList(roleIdOfIdMap.keySet(), roleIdList);
        // 转换成主键id 批量删除
        if (CollUtil.isNotEmpty(deleteRoleIdList)) {
            this.removeBatchByIds(deleteRoleIdList.stream().map(roleIdOfIdMap::get).toList());
        }
        // 需要添加的角色id
        List<Long> saveRoleIdList = CollUtil.subtractToList(roleIdList, roleIdOfIdMap.keySet());
        // 批量添加
        this.saveBatch(saveRoleIdList.stream().map(roleId -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            return sysUserRole;
        }).toList());
    }
}